<template>
  <div class="auth-container">
    <!-- 左侧背景图 -->
    <div class="auth-side">
      <div class="side-content">
        <h2>欢迎使用 offer多多</h2>
        <p>便捷、高效的岗位汇集系统</p>
      </div>
    </div>

    <!-- 右侧表单区域 -->
    <div class="auth-form">
      <!-- 标签页切换 -->
      <div class="tabs">
        <button
          :class="['tab', { active: activeTab === 'login' }]"
          @click="activeTab = 'login'"
        >
          登录
        </button>
        <button
          :class="['tab', { active: activeTab === 'register' }]"
          @click="activeTab = 'register'"
        >
          注册
        </button>
      </div>

      <!-- 登录表单 -->
      <el-form
        v-if="activeTab === 'login'"
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        @submit.prevent="handleLogin"
        class="form"
      >
        <!-- 登录方式切换 -->
        <el-radio-group v-model="loginMethod" class="method-toggle">
          <el-radio-button label="password">密码登录</el-radio-button>
          <el-radio-button label="code">验证码登录</el-radio-button>
        </el-radio-group>

        <!-- 账号输入 -->
        <el-form-item prop="account">
          <el-input
            v-model="loginForm.account"
            placeholder="请输入邮箱或手机号"
            :type="isEmail(loginForm.account) ? 'email' : 'text'"
            clearable
          />
        </el-form-item>

        <!-- 密码输入（仅密码登录） -->
        <el-form-item v-if="loginMethod === 'password'" prop="password">
          <el-input
            v-model="loginForm.password"
            placeholder="请输入密码"
            type="password"
            show-password
            clearable
          />
        </el-form-item>

        <!-- 验证码输入（仅验证码登录） -->
        <el-form-item v-else prop="code">
          <el-input
            v-model="loginForm.code"
            placeholder="请输入验证码"
            maxlength="6"
            clearable
          >
            <template #append>
              <el-button
                :disabled="countdown > 0"
                @click="sendLoginCode"
              >
                {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-button type="primary" native-type="submit" class="submit-btn" size="large">
          {{ loginMethod === 'password' ? '立即登录' : '验证登录' }}
        </el-button>

        <div class="links">
          <span>没有账号？</span>
          <a href="#" @click.prevent="activeTab = 'register'">立即注册</a>
        </div>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        @submit.prevent="handleRegister"
        class="form"
      >
        <!-- 注册类型选择 -->
        <el-radio-group v-model="registerType" class="method-toggle">
          <el-radio-button label="email">邮箱注册</el-radio-button>
          <el-radio-button label="phone" disabled>手机注册</el-radio-button>
        </el-radio-group>

        <!-- 邮箱/手机输入 -->
        <el-form-item prop="account">
          <el-input
            v-model="registerForm.account"
            :placeholder="registerType === 'email' ? '请输入邮箱' : '请输入手机号'"
            :type="registerType === 'email' ? 'email' : 'tel'"
            clearable
          />
        </el-form-item>

        <!-- 验证码输入 -->
        <el-form-item prop="code">
          <el-input
            v-model="registerForm.code"
            placeholder="请输入验证码"
            maxlength="6"
            clearable
          >
            <template #append>
              <el-button
                :disabled="countdown > 0"
                @click="sendRegisterCode"
              >
                {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            placeholder="请设置密码（6-16位）"
            type="password"
            show-password
            minlength="6"
            maxlength="16"
            clearable
          />
        </el-form-item>

        <!-- 新增确认密码输入 -->
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            placeholder="请确认密码"
            type="password"
            show-password
            minlength="6"
            maxlength="16"
            clearable
          />
        </el-form-item>

        <el-button type="primary" native-type="submit" class="submit-btn" size="large">
          立即注册
        </el-button>

        <div class="links">
          <span>已有账号？</span>
          <a href="#" @click.prevent="activeTab = 'login'">立即登录</a>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { sendCodeApi, loginApi, registerApi } from '../api/Login.js'
import {JmApi,decryptPassword}from '../api/jm.js'

// 当前激活的标签页
const activeTab = ref('login')

// ========== 登录相关 ==========
const loginMethod = ref('password')
const loginForm = reactive({
  account: '',
  password: '',
  code: '',
  loginType: ''
})
const loginFormRef = ref(null)

// ========== 注册相关 ==========
const registerType = ref('email')
const registerForm = reactive({
  account: '',
  code: '',
  password: '',
  confirmPassword: '',
  loginType: ''
})

// 注册表单规则
const registerRules = {
  account: [
    { required: true, message: '请输入邮箱或手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) return callback()
        const isValid = registerType.value === 'email'
          ? isEmail(value)
          : /^1[3-9]\d{9}$/.test(value)
        if (!isValid) {
          callback(new Error(`${registerType.value === 'email' ? '邮箱' : '手机号'}格式不正确`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const registerFormRef = ref(null)

// 倒计时
const countdown = ref(0)

// 检查是否为邮箱
const isEmail = (str) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(str)
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 发送登录验证码
const sendLoginCode = async () => {
  // 验证账号格式
  if (!loginForm.account.trim()) {
    ElMessage.error('请输入邮箱或手机号')
    return
  }

  const isValid = isEmail(loginForm.account) || /^1[3-9]\d{9}$/.test(loginForm.account)
  if (!isValid) {
    ElMessage.error('请输入正确的邮箱或手机号')
    return
  }
  
  // 发送验证码请求
  if(isEmail(loginForm.account)){
    loginForm.loginType = 'emailcode'
    loginForm.email = loginForm.account
  }else{
    loginForm.loginType = 'phonecode'
    loginForm.phone = loginForm.account
  }
  
  startCountdown();

  const result = await sendCodeApi(loginForm); 
  console.log(result);
  if (result.code === 1) {
    ElMessage.success('验证码已发送，请注意查收');
  } else {
    ElMessage.error(result.message);
  }
}

// 发送注册验证码
const sendRegisterCode = async () => {
  if (!registerForm.account.trim()) {
    ElMessage.error(`请输入${registerType.value === 'email' ? '邮箱' : '手机号'}`)
    return
  }

  const isValid = registerType.value === 'email'
    ? isEmail(registerForm.account)
    : /^1[3-9]\d{9}$/.test(registerForm.account)

  if (!isValid) {
    ElMessage.error(`请输入正确的${registerType.value === 'email' ? '邮箱' : '手机号'}`)
    return
  }

  // 发送验证码请求
  if(isEmail(registerForm.account)){
    registerForm.loginType = 'emailcode'
    registerForm.email = registerForm.account
  }else{
    registerForm.loginType = 'phonecode'
    registerForm.phone = registerForm.account
  }
  
  startCountdown();
  const result = await sendCodeApi(registerForm);
  console.log(result);
  if (result.code === 1) {
    ElMessage.success('验证码已发送，请注意查收');
  } else {
    ElMessage.error(result.message);
  }
}

// 登录表单规则
const loginRules = {
  account: [
    { required: true, message: '请输入邮箱或手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) return callback()
        const isValid = isEmail(value) || /^1[3-9]\d{9}$/.test(value)
        if (!isValid) {
          callback(new Error('邮箱或手机号格式不正确'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if(loginForm.account === ''){
    ElMessage.error('请输入邮箱或手机号');
    return;
  }
  if(loginForm.password === ''&& loginMethod.value === 'password'){
    ElMessage.error('请输入密码');
    return;
  }

  if(loginMethod.value === 'password' && loginForm.password.length < 6 || loginForm.password.length > 16){
    ElMessage.error('密码长度不合规');
    return;
  }

  if(loginMethod.value === 'code' && loginForm.code === ''){
    ElMessage.error('请输入验证码');
    return;
  }

  if(loginMethod.value === 'code' && loginForm.code.length !== 6){
    ElMessage.error('验证码长度不合规');
    return;
  }

  if(isEmail(loginForm.account)){
    loginForm.email = loginForm.account
      if(loginMethod.value === 'password'){
      loginForm.loginType = 'emailpassword'
      }else{
      loginForm.loginType = 'emailcode'
      }
  }else{
    loginForm.phone = loginForm.account
    if(loginMethod.value === 'password'){
      loginForm.loginType = 'phonepassword'
      }else{
      loginForm.loginType = 'phonecode'
      }
  }
  // 密码加密
  loginForm.password = await JmApi(loginForm.password)
  const result = await loginApi(loginForm);
  localStorage.setItem('token', result.data)
  if (result.code === 1) {
    ElMessage.success(result.message);
    // 跳转到首页
    // 等待1.5s
    setTimeout(() => {
      window.location.href = '/';
    }, 1500);
  } else {
    loginForm.password = await decryptPassword(loginForm.password)
    if(result.message === 'CodeExpired')
    ElMessage.error("验证码已经过期");
    else if(result.message === 'CodeError')
    ElMessage.error("验证码错误");
    else if(result.message === 'PasswordError')
    ElMessage.error("密码错误");
    else ElMessage.error(result.message);
  }
}

// 处理注册
const handleRegister = async () => {
  if(registerForm.account === ''){
    ElMessage.error('请输入邮箱或手机号');
    return;
  }
  if(registerForm.password === ''){
    ElMessage.error('请输入密码');
    return;
  }
  if(registerForm.password.length < 6 || registerForm.password.length > 16){
    ElMessage.error('密码长度不合规');
    return;
  }
  if(registerForm.confirmPassword === ''){
    ElMessage.error('请确认密码');
    return;
  }
  if(registerForm.confirmPassword !== registerForm.password){
    ElMessage.error('两次输入的密码不一致');
    return;
  }
  if(registerForm.code === ''){
    ElMessage.error('请输入验证码');
    return;
  }
  if(registerForm.code.length !== 6){
    ElMessage.error('验证码长度不合规');
    return;
  }
  if(isEmail(registerForm.account)){
    registerForm.email = registerForm.account
    registerForm.loginType = 'emailcode'
  }else{
    registerForm.phone = registerForm.account
    registerForm.loginType = 'phonecode'
  }
  // 密码加密
  registerForm.confirmPassword = await JmApi(registerForm.confirmPassword)
  registerForm.password = await JmApi(registerForm.password)
  const result = await registerApi(registerForm);
  if (result.code === 1) {
    ElMessage.success('注册成功，请登录！')
    activeTab.value = 'login'
    loginForm.account = registerForm.account
    loginForm.password = decryptPassword(registerForm.password)
  } else {
    registerForm.password = await decryptPassword(registerForm.password)
    registerForm.confirmPassword = await decryptPassword(registerForm.confirmPassword)
    if(result.message === 'ExitsEmail')
    ElMessage.error("邮箱已注册");
    else if(result.message === 'ExitsPhone')
    ElMessage.error("手机号已注册");
    else if(result.message === 'CodeExpired')
    ElMessage.error("验证码已经过期");
    else if(result.message === 'CodeError')
    ElMessage.error("验证码错误");
    else
    ElMessage.error(result.message);
  }
}

</script>

<style scoped>
.auth-container {
  display: flex;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 左侧背景 */
/* 左侧背景 - 动态大跨度渐变 */
.auth-side {
  flex: 1;
  /* 初始渐变方向，会被动画改变 */
  background: linear-gradient(45deg, 
    #12005e,   /* 深蓝紫 */
    #667eea,   /* 蓝 */
    #4ade80,   /* 亮绿 */
    #fbbf24,   /* 橙黄 */
    #ec4899    /* 粉紫 */
  );
  background-size: 400% 400%; /* 必须大于 100% 才能实现动画位移 */
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  animation: gradientShift 20s ease infinite; /* 缓慢循环动画 */
}

/* 渐变位置位移动画 */
@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* 可选：增加文字轻微浮现效果 */
.side-content h2,
.side-content p {
  opacity: 0;
  animation: fadeIn 2s ease-out forwards;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 保持原有文字样式 */
.side-content h2 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  animation-delay: 0.3s;
}

.side-content p {
  font-size: 1.2rem;
  opacity: 0.95;
  animation-delay: 0.8s;
}

.side-content h2 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}

.side-content p {
  font-size: 1.2rem;
  opacity: 0.9;
}

/* 表单容器 - 增加阴影和圆角 */
.auth-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 3rem;
  background-color: #f8f9fa;
  box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 15px;
}

/* 输入框 - 聚焦时的动画 */
.el-input__inner {
  transition: all 0.3s ease;
  border-radius: 8px;
}

.el-input__inner:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
  transform: scale(1.02);
  outline: none;
}

/* 提交按钮 - 悬停效果 */
.submit-btn {
  width: 100%;
  margin-top: 1rem;
  transition: all 0.3s ease-in-out;
}

.submit-btn:hover {
  background-color: darken(#007bff, 10%);
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
}

/* 标签页 - 切换时的过渡效果 */
.tab {
  transition: color 0.3s ease, border-bottom-color 0.3s ease;
}

.tab.active::after {
  transition: bottom 0.3s ease, background-color 0.3s ease;
}

/* 链接 - 悬停下划线 */
.links a {
  position: relative;
  transition: all 0.3s ease;
}

.links a::before {
  content: '';
  position: absolute;
  width: 0;
  height: 2px;
  bottom: 0;
  left: 0;
  background-color: #007bff;
  transition: width 0.3s ease;
}

.links a:hover::before {
  width: 100%;
}

.tabs {
  display: flex;
  margin-bottom: 2rem;
  border-bottom: 1px solid #dee2e6;
}

.tab {
  padding: 1rem 2rem;
  background: none;
  border: none;
  font-size: 1.1rem;
  cursor: pointer;
  color: #6c757d;
  position: relative;
}

.tab.active {
  color: #495057;
  font-weight: 600;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 3px;
  background-color: #007bff;
}

.form {
  max-width: 400px;
  width: 100%;
  margin: 0 auto;
}

.form h3 {
  text-align: center;
  color: #333;
  margin-bottom: 1.5rem;
  font-weight: 600;
}

.method-toggle {
  margin-bottom: 1.5rem;
}

.input-group {
  margin-bottom: 1rem;
}

.submit-btn {
  width: 100%;
  margin-top: 1rem;
}

.links {
  text-align: center;
  margin-top: 1.5rem;
  color: #6c757d;
  font-size: 0.9rem;
}

.links a {
  color: #007bff;
  text-decoration: none;
  margin-left: 0.5rem;
}

.links a:hover {
  text-decoration: underline;
}

/* 响应式 */
@media (max-width: 768px) {
  .auth-container {
    flex-direction: column;
  }
  .auth-side {
    padding: 1.5rem;
  }
  .auth-side h2 {
    font-size: 2rem;
  }
  .auth-form {
    padding: 2rem 1.5rem;
  }
}
</style>